package com.jozen.smart_toilet_system.tagView;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;

import com.jozen.modelbase.netwoek.util.DensityUtil;
import com.jozen.smart_toilet_system.bean.BathroomModel;


/**
 * 自定义茅坑坑位展示页
 */
public class PictureTagShowLayout extends RelativeLayout {
    private int width, height;

    public PictureTagShowLayout(Context context) {
        super(context, null);
    }

    public PictureTagShowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PictureTagShowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    /**
     * 坑位配置数据
     *
     * @param bathroomModel
     */
    public void setData(BathroomModel bathroomModel) {
        removeAllViews();
        invalidate();
        if (bathroomModel != null && bathroomModel.getControls().size() > 0) {
            for (BathroomModel.ControlsDTO model : bathroomModel.getControls()) {
                showTag(model.getX(), model.getY(), model.getStatus(),model.isSos());
            }
        }
    }

    /**
     * 当前控件宽高
     *
     * @param w
     * @param h
     */
    public void setWidthHeight(int w, int h) {
        this.width = w;
        this.height = h;
    }

    /**
     * 显示已经添加过的TAG
     *
     * @param x
     * @param y
     */
    private void showTag(int x, int y, int state,boolean sos) {
        View view = null;
        LayoutParams params = new LayoutParams(DensityUtil.dip2px(getContext(), 50), DensityUtil.dip2px(getContext(), 50));
        if (x > getWidth() * 0.5) {
            params.leftMargin = x - PictureTagView.getViewWidth()+25;
            view = new PictureTagView(getContext(), PictureTagView.Direction.Right);
        } else {
            params.leftMargin = x - 25;
            view = new PictureTagView(getContext(), PictureTagView.Direction.Left);
        }

        params.topMargin = y - 25;
        //上下位置在视图内
        if (params.topMargin < 0) {
            params.topMargin = 0;
        } else if ((params.topMargin + PictureTagView.getViewHeight()) > getHeight()) {
            params.topMargin = getHeight() - PictureTagView.getViewHeight();
            if (params.topMargin < 0) {
                params.topMargin = y - 25;
            }
        }
        view.setTag(x + "tag" + y);
        ((PictureTagView) view).setIcon(((PictureTagView) view).getBgIcon(state, sos),sos,state);
        this.addView(view, params);

        View finalView = view;
        //每个添加的TagView设置点击监听事件
        finalView.setOnClickListener(v -> {
            PictureTagView tagView = (PictureTagView) v;
            String tag = (String) tagView.getTag();
        });
    }
}
